import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import Label, Canvas, PhotoImage
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# 设置中文字体支持
plt.rcParams["font.family"] = ["SimHei","KaiTi"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题

# 生成或导入自建数据集
data = {
    'id': np.arange(1, 1001),
    'age': np.random.randint(18, 61, size=1000),
    'income': np.random.normal(5000, 1000, size=1000).astype(int),
    'education_level': np.random.choice(['高中', '本科', '硕士', '博士'], size=1000)
}
df = pd.DataFrame(data)

# 第一类可视化：年龄分布直方图
def show_age_distribution():
    fig1 = plt.figure(figsize=(8, 6))
    plt.hist(df['age'], bins=20, edgecolor='black', color='skyblue')
    plt.title('年龄分布直方图')
    plt.xlabel('年龄')
    plt.ylabel('频数')
    
    root1 = tk.Tk()
    root1.title('年龄分布')
    root1.geometry('800x600')
    
    canvas1 = FigureCanvasTkAgg(fig1, master=root1)
    canvas1.draw()
    canvas1.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    
    btn_close1 = tk.Button(root1, text="关闭", command=root1.destroy)
    btn_close1.pack(pady=10)
    
    root1.mainloop()

# 第二类可视化：不同教育水平的收入趋势折线图
def show_income_trend():
    fig2 = plt.figure(figsize=(12, 7))
    
    # 按年龄分组并计算各教育水平的平均收入
    age_bins = np.arange(18, 61, 5)  # 每5岁为一个年龄段
    age_labels = [f'{age}-{age+4}' for age in age_bins[:-1]]
    
    # 创建一个新的年龄分组列
    df['age_group'] = pd.cut(df['age'], bins=age_bins, labels=age_labels, right=False)
    
    # 计算各年龄段、各教育水平的平均收入
    pivot_table = df.pivot_table(index='age_group', columns='education_level', values='income', aggfunc='mean',observed=False)
    
    # 绘制折线图
    line_styles = ['-', '--', '-.', ':']
    markers = ['o', 's', '^', 'D']
    
    for i, level in enumerate(pivot_table.columns):
        plt.plot(pivot_table.index, pivot_table[level], line_styles[i], marker=markers[i], 
                 linewidth=2, markersize=8, label=level)
    
    plt.title('不同教育水平人群的收入趋势变化')
    plt.xlabel('年龄段')
    plt.ylabel('平均收入')
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.legend(title='教育水平', loc='upper left')
    plt.xticks(rotation=45)
    plt.tight_layout()
    
    root2 = tk.Tk()
    root2.title('教育水平与收入趋势')
    root2.geometry('1200x700')
    
    canvas2 = FigureCanvasTkAgg(fig2, master=root2)
    canvas2.draw()
    canvas2.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    
    btn_close2 = tk.Button(root2, text="关闭", command=root2.destroy)
    btn_close2.pack(pady=10)
    
    root2.mainloop()

# 第三类可视化：各教育水平人数饼图
def show_education_pie():
    edu_counts = df['education_level'].value_counts()
    fig3 = plt.figure(figsize=(8, 8))
    plt.pie(edu_counts, labels=edu_counts.index, autopct='%1.1f%%', 
            startangle=90, shadow=True, explode=(0.1, 0, 0, 0))
    plt.title('教育水平分布')
    
    root3 = tk.Tk()
    root3.title('教育水平分布')
    root3.geometry('800x800')
    
    canvas3 = FigureCanvasTkAgg(fig3, master=root3)
    canvas3.draw()
    canvas3.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    
    btn_close3 = tk.Button(root3, text="关闭", command=root3.destroy)
    btn_close3.pack(pady=10)
    
    root3.mainloop()

# 第四类可视化：年龄与收入散点图
def show_age_income_scatter():
    fig4 = plt.figure(figsize=(10, 6))
    scatter = plt.scatter(df['age'], df['income'], alpha=0.5, 
                          c=df['age'], cmap='viridis')
    plt.colorbar(label='年龄')
    plt.title('年龄与收入关系散点图')
    plt.xlabel('年龄')
    plt.ylabel('收入')
    
    # 添加趋势线
    z = np.polyfit(df['age'], df['income'], 1)
    p = np.poly1d(z)
    plt.plot(df['age'], p(df['age']), "r--")
    
    root4 = tk.Tk()
    root4.title('年龄与收入关系')
    root4.geometry('1000x600')
    
    canvas4 = FigureCanvasTkAgg(fig4, master=root4)
    canvas4.draw()
    canvas4.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    
    btn_close4 = tk.Button(root4, text="关闭", command=root4.destroy)
    btn_close4.pack(pady=10)
    
    root4.mainloop()

# 创建主菜单
def main_menu():
    main = tk.Tk()
    main.title('数据可视化菜单')
    main.geometry('400x500')
    
    Label(main, text="选择要查看的可视化图表", font=('Arial', 14)).pack(pady=20)
    
    btn1 = tk.Button(main, text="1. 年龄分布直方图", command=show_age_distribution, 
                    width=30, height=2, font=('Arial', 12))
    btn1.pack(pady=10)
    
    btn2 = tk.Button(main, text="2. 教育水平与收入趋势图", command=show_income_trend, 
                    width=30, height=2, font=('Arial', 12))
    btn2.pack(pady=10)
    
    btn3 = tk.Button(main, text="3. 教育水平分布饼图", command=show_education_pie, 
                    width=30, height=2, font=('Arial', 12))
    btn3.pack(pady=10)
    
    btn4 = tk.Button(main, text="4. 年龄与收入散点图", command=show_age_income_scatter, 
                    width=30, height=2, font=('Arial', 12))
    btn4.pack(pady=10)
    
    btn_exit = tk.Button(main, text="退出", command=main.destroy, 
                        width=15, height=1, font=('Arial', 10))
    btn_exit.pack(pady=20)
    
    main.mainloop()

# 启动程序
if __name__ == "__main__":
    main_menu()